package com.xiaohei.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaohei.auth.service.SysMenuService;
import com.xiaohei.auth.service.SysRoleMenuService;
import com.xiaohei.auth.service.SysUserService;
import com.xiaohei.common.JWT.JWTHelper;
import com.xiaohei.common.config.exception.XiaoheiException;
import com.xiaohei.common.result.Result;
import com.xiaohei.common.utils.MD5;
import com.xiaohei.model.system.SysMenu;
import com.xiaohei.model.system.SysRoleMenu;
import com.xiaohei.model.system.SysUser;
import com.xiaohei.vo.system.LoginVo;
import com.xiaohei.vo.system.RouterVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: IndexController
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/4/22 20:04
 * Version 1.0
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 登录
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo){
//        {"code":20000,"data":{"token":"admin-token"}}
//        String data = "{\"code\":20000,\"data\":{\"token\":\"admin-token\"}}";
//        return Result.ok(data);

//        Map<String,Object> map = new HashMap<>();
//        map.put("token","admin-token");
//        return Result.ok(map);

        //1. 获取输入的用户名和密码
        String username = loginVo.getUsername();
        //2. 根据用户名查询数据库是否存在
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
        //3. 用户信息是否存在
        if(sysUser == null){
            throw new XiaoheiException(201,"用户不存在");
        }
        //4. 判断密码是否正确
        //数据库密码
        String passwordDB = sysUser.getPassword();
        //用户输入的密码加密
        String encrypt = MD5.encrypt(loginVo.getPassword());
        if(!passwordDB.equals(encrypt)){
            throw new XiaoheiException(201,"密码错误");
        }
        //5. 判断用户是否被禁用  1可用  0禁用
        if(sysUser.getStatus().intValue() == 0){
            throw new XiaoheiException(201,"用户被禁用");
        }
        //6. 使用JWT根据用户id和名称生成token进行返回
        String token = JWTHelper.createToken(sysUser.getId(), sysUser.getUsername());

        //返回
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("token",token);
        return Result.ok(map);
    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("info")
    public Result info(HttpServletRequest request){
//        {
//            "code": 20000,
//            "data": {
//              "roles": ["admin"],
//              "introduction": "I am a super administrator",
//              "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
//              "name": "Super Admin"
//          }
//        }
        //1. 从请求头中获取用户信息（头中的token）
        String token = request.getHeader("token");
        //2. 获取用户id/名称
        Long userId = JWTHelper.getUserId(token);
        String username = JWTHelper.getUsername(token);
        //3. 根据用户id查询数据库，把用户信息获取出来
        SysUser sysUser = sysUserService.getById(userId);
        //4. 根据用户id列表获取用户可以操作菜单列表
        //查询数据库  动态构建路由页面显示
        List<RouterVo> routerList = sysMenuService.findUserMenuListByUserId(userId);

        //5. 根据用户id 获取用户可以操作菜单列表
        List<String> permsList = sysMenuService.findMenuPermsByUserId(userId);

        //6. 返回响应的数据
        Map<String,Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name",sysUser.getName());
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        //返回用户可以操作的菜单
        map.put("routers",routerList);
        //返回用户可以操作的按钮
        map.put("buttons",permsList);
        return Result.ok(map);
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }

}
